package backtracking;

import java.util.*;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class combinationSum2 {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0);
        return result;
    }
    public void backtracking(int[] candidates, int target, int sum, int idx) {
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = idx; i < candidates.length; i++) {
            if (i > idx && candidates[i] == candidates[i-1]){
                continue;
            }
            if (sum + candidates[i] > target) {
                break;
            }
            path.add(candidates[i]);
            backtracking(candidates, target, sum + candidates[i], i + 1);
            path.remove(path.size() - 1);
        }
    }
}
